package org.jeecg.modules.business.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.business.dto.UserGroupDto;
import org.jeecg.modules.business.dto.UserLabelDto;
import org.jeecg.modules.business.entity.*;
import org.jeecg.modules.business.service.*;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.business.vo.MemberCardStatVo;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.modules.mall.entity.MallUserInfo;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: bus_member_card
 * @Author: jeecg-boot
 * @Date:   2023-03-10
 * @Version: V1.0
 */
@Api(tags="bus_member_card")
@RestController
@RequestMapping("/business/busMemberCard")
@Slf4j
public class BusMemberCardController extends JeecgController<BusMemberCard, IBusMemberCardService> {
	@Autowired
	private IBusMemberCardService busMemberCardService;
	@Resource
	private IBusCustomerService busCustomerService;
	 @Autowired
	 private IBusHotelService busHotelService;
	 @Autowired
	 private IBusMarketMemberService busMarketMemberService;
	 @Autowired
	 private IBusMarketMemberGroupService busMarketMemberGroupService;
	 @Autowired
	 private IBusMarketMemberLableService busMarketMemberLableService;
	 @Resource
	 private IService<MallUserInfo> mallUserInfoIService;
	 @Resource
	 private ISysUserService sysUserService;
	/**
	 * 分页列表查询
	 *
	 * @param busMemberCard
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "bus_member_card-分页列表查询")
	@ApiOperation(value="bus_member_card-分页列表查询", notes="bus_member_card-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<BusMemberCard>> queryPageList(BusMemberCard busMemberCard,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
													  @RequestParam(name="startTime",required = false) String startTime,
													  @RequestParam(name="endTime",required = false) String endTime,
													  @RequestParam(name="hotelIds[]",required = false) List<String> hotelIds,
								   HttpServletRequest req) {
		LambdaQueryWrapper<BusMemberCard> queryWrapper = QueryGenerator.initQueryWrapper(busMemberCard, req.getParameterMap()).lambda();
		if (ObjectUtils.isNotEmpty(startTime)) {
			queryWrapper.ge(BusMemberCard::getCreateTime, DateUtil.parseDate(startTime));
		}
		if (ObjectUtils.isNotEmpty(endTime)) {
			queryWrapper.le(BusMemberCard::getCreateTime, DateUtil.parseDate(endTime));
		}
		if (ObjectUtils.isNotEmpty(hotelIds)) {
			queryWrapper.and(j -> {
				for (int k = 0; k < hotelIds.size(); k++) {
					j = j.or().eq(BusMemberCard::getHotelId, hotelIds.get(k));
				}
			});
		}
		Page<BusMemberCard> page = new Page<BusMemberCard>(pageNo, pageSize);
		IPage<BusMemberCard> pageList = busMemberCardService.page(page, queryWrapper);
		pageList.getRecords().forEach(item -> {
			BusHotel hotle = busHotelService.getById(item.getHotelId());
			if (hotle != null) {
				item.setHotelName(hotle.getName());
			}
			BusMarketMember busMarketMember = busMarketMemberService.getById(item.getGradeId());
			if (busMarketMember != null) {
				item.setGradeName(busMarketMember.getName());
			}
			if (ObjectUtils.isNotEmpty(item.getGroupId())) {
				BusMarketMemberGroup busMarketMemberGroup = busMarketMemberGroupService.getById(item.getGroupId());
				if (busMarketMemberGroup != null) {
					item.setGroupName(busMarketMemberGroup.getName());
				}
			}
			if (ObjectUtils.isNotEmpty(item.getLabelId())) {
				BusMarketMemberLable busMarketMemberLable = busMarketMemberLableService.getById(item.getLabelId());
				if (busMarketMemberLable != null) {
					item.setLabelName(busMarketMemberLable.getName());
				}
			}
		});
		return Result.OK(pageList);
	}

	/**
	 * 会员各种统计
	 * @param hotelId
	 * @return
	 */
	 @GetMapping(value = "/stat")
	 public Result stat(@RequestParam(name="hotelId") String hotelId) {
		 MemberCardStatVo vo = busMemberCardService.stat(hotelId);
		 return Result.OK(vo);
	 }

	/**
	 *   添加
	 *
	 * @param busMemberCard
	 * @return
	 */
	@AutoLog(value = "bus_member_card-添加")
	@ApiOperation(value="bus_member_card-添加", notes="bus_member_card-添加")
	//@RequiresPermissions("business:bus_member_card:add")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody BusMemberCard busMemberCard) {
		LoginUser user = TokenUtils.getAuthUser();
		if (user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")) {
			busMemberCard.setTenantId(user.getRelTenantIds());
		} else {
			throw new JeecgBootException("当前登录人租户信息错误");
		}
		LambdaQueryWrapper<BusMemberCard> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(BusMemberCard::getMobile, busMemberCard.getMobile());
		queryWrapper.eq(BusMemberCard::getHotelId, busMemberCard.getHotelId()).last("limit 1");
		BusMemberCard memeber = busMemberCardService.getOne(queryWrapper);
		if (memeber != null) {
			return Result.error("该手机号已存在！");
		}
		LambdaQueryWrapper<MallUserInfo> queryWrapper2 = new LambdaQueryWrapper<>();
		queryWrapper2.eq(MallUserInfo::getMobile, busMemberCard.getMobile());
		queryWrapper2.eq(MallUserInfo::getTenantId, busMemberCard.getTenantId()).last("limit 1");
		MallUserInfo mallUserInfo = mallUserInfoIService.getOne(queryWrapper2);
		if (mallUserInfo != null) {
			busMemberCard.setUserId(mallUserInfo.getId());
		}
		busMemberCardService.save(busMemberCard);
		BusCustomer busCustomer = new BusCustomer();
		busCustomer.setRelationVipId(busMemberCard.getId());
		busCustomer.setTenantId(user.getRelTenantIds());
		busCustomer.setHotelId(busMemberCard.getHotelId());
		busCustomer.setName(busMemberCard.getName());
		busCustomer.setGender(busMemberCard.getSex());
		busCustomer.setPhone(busMemberCard.getMobile());
		busCustomer.setCertType(busMemberCard.getCertificateType());
		busCustomer.setCertNo(busMemberCard.getCertificateNo());
		busCustomer.setPhone(busMemberCard.getMobile());
		busCustomer.setAddress(busMemberCard.getAddress());
		busCustomerService.save(busCustomer);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param busMemberCard
	 * @return
	 */
	@AutoLog(value = "bus_member_card-编辑")
	@ApiOperation(value="bus_member_card-编辑", notes="bus_member_card-编辑")
	//@RequiresPermissions("business:bus_member_card:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody BusMemberCard busMemberCard) {
		LambdaQueryWrapper<BusMemberCard> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(BusMemberCard::getMobile, busMemberCard.getMobile());
		queryWrapper.eq(BusMemberCard::getHotelId,busMemberCard.getHotelId());
		queryWrapper.ne(BusMemberCard::getId,busMemberCard.getId()).last("limit 1");
		BusMemberCard memeber = busMemberCardService.getOne(queryWrapper);
		if (memeber != null) {
			return Result.error("该手机号已存在！");
		}
		busMemberCardService.updateById(busMemberCard);
		return Result.OK("编辑成功!");
	}

	 @AutoLog(value = "用户批量分组")
	 @ApiOperation(value="用户批量分组", notes="用户批量分组")
	 @RequestMapping(value = "/groupBatch", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> groupBatch(@RequestBody UserGroupDto dto) {
		 Result res = busMemberCardService.groupBatch(dto);
		 return res;
	 }

	 @AutoLog(value = "用户批量标签")
	 @ApiOperation(value="用户批量标签", notes="用户批量标签")
	 @RequestMapping(value = "/lableBatch", method = {RequestMethod.PUT,RequestMethod.POST})
	 public Result<String> lableBatch(@RequestBody UserLabelDto dto) {
		 Result res = busMemberCardService.lableBatch(dto);
		 return res;
	 }

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "bus_member_card-通过id删除")
	@ApiOperation(value="bus_member_card-通过id删除", notes="bus_member_card-通过id删除")
	//@RequiresPermissions("business:bus_member_card:delete")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		BusMemberCard member = busMemberCardService.getById(id);
		if (member != null) {
			if (member.getIntegral() > 0) {
				return Result.error("剩余可用积分不可删除!");
			}
			if (member.getBalance().compareTo(BigDecimal.ZERO)>0) {
				return Result.error("剩余可用余额不可删除!");
			}
		}
		busMemberCardService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "bus_member_card-批量删除")
	@ApiOperation(value="bus_member_card-批量删除", notes="bus_member_card-批量删除")
	//@RequiresPermissions("business:bus_member_card:deleteBatch")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		List<String> idList = Arrays.asList(ids.split(","));
		if (ObjectUtils.isNotEmpty(idList)) {
			for (int i = 0; i < idList.size(); i++) {
				BusMemberCard member = busMemberCardService.getById(idList.get(i));
				if (member != null) {
					if (member.getIntegral() > 0) {
						return Result.error("剩余可用积分不可删除!");
					}
					if (member.getBalance().compareTo(BigDecimal.ZERO) > 0) {
						return Result.error("剩余可用余额不可删除!");
					}
				}
			}
		}
		this.busMemberCardService.removeByIds(idList);
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "bus_member_card-通过id查询")
	@ApiOperation(value="bus_member_card-通过id查询", notes="bus_member_card-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<BusMemberCard> queryById(@RequestParam(name="id",required=true) String id) {
		BusMemberCard busMemberCard = busMemberCardService.getById(id);
		if(busMemberCard==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(busMemberCard);
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "bus_member_card-通过id查询")
	@ApiOperation(value="通过会员id找到会员卡等级", notes="bus_member_card-通过id查询")
	@GetMapping(value = "/getMarkerMemberByCarId")
	public Result<BusMarketMember> getMarkerMemberByCarId(@RequestParam(name="id",required=true) String id) {
		return Result.OK(busMemberCardService.getMarkerMemberByCarId(id));
	}

    /**
    * 导出excel
    *
    * @param request
    * @param busMemberCard
    */
    //@RequiresPermissions("business:bus_member_card:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, BusMemberCard busMemberCard) {
        return exportXls2(request, busMemberCard, BusMemberCard.class, "会员列表");
    }

	private ModelAndView exportXls2(HttpServletRequest request, BusMemberCard object, Class<BusMemberCard> clazz, String title) {
		// Step.1 组装查询条件
		QueryWrapper<BusMemberCard> queryWrapper = QueryGenerator.initQueryWrapper(object, request.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		// 过滤选中数据
		String selections = request.getParameter("selections");
		if (oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			queryWrapper.in("id", selectionList);
		}
		// Step.2 获取导出数据
		List<BusMemberCard> exportList = service.list(queryWrapper);
		exportList.forEach(t -> {
			BusHotel busHotel = busHotelService.getById(t.getHotelId());
			if (busHotel != null) {
				t.setHotelId(busHotel.getName());
			}
			BusMarketMember busMarketMember = busMarketMemberService.getById(t.getGradeId());
			if (busMarketMember != null) {
				t.setGradeId(busMarketMember.getName());
			}
			SysUser sysUser1=sysUserService.getById(t.getStaffId());
			if(sysUser1!=null) {
				t.setStaffId(sysUser1.getRealname());
			}
		});
		// Step.3 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		//此处设置的filename无效 ,前端会重更新设置一下
		mv.addObject(NormalExcelConstants.FILE_NAME, title);
		mv.addObject(NormalExcelConstants.CLASS, clazz);
		//update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
		ExportParams exportParams = new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title);
		exportParams.setImageBasePath(this.upLoadPath);
		//update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
		mv.addObject(NormalExcelConstants.PARAMS, exportParams);
		mv.addObject(NormalExcelConstants.DATA_LIST, exportList);
		return mv;
	}

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("business:bus_member_card:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response,@RequestParam(name="hotelId",required=true) String hotelId) {
        return importExcel2(request, response, BusMemberCard.class,hotelId);
    }


	private Result<?> importExcel2(HttpServletRequest request, HttpServletResponse response, Class<BusMemberCard> clazz,String hotelId) {
		LoginUser user = TokenUtils.getAuthUser();
		if (user.getRelTenantIds() != null && !user.getRelTenantIds().equals("")) {
		} else {
			throw new JeecgBootException("当前登录人租户信息错误");
		}
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取上传文件对象
			MultipartFile file = entity.getValue();
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<BusMemberCard> list = ExcelImportUtil.importExcel(file.getInputStream(), clazz, params);
//				log.info(JSON.toJSONString(list));
				//update-begin-author:taoyan date:20190528 for:批量插入数据
				long start = System.currentTimeMillis();

				List<BusMemberCard> addList = new ArrayList<>();
				list.forEach(t -> {
					if (StringUtils.isNotBlank(t.getGradeId())) {
						LambdaQueryWrapper<BusMemberCard> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
						lambdaQueryWrapper2.eq(BusMemberCard::getHotelId, hotelId);
						lambdaQueryWrapper2.and(o -> {
							o.or().eq(BusMemberCard::getCardNo, t.getCardNo());
							o.or().eq(BusMemberCard::getMobile, t.getMobile());
							o.or().eq(BusMemberCard::getCertificateNo, t.getCertificateNo());
						});
						Long count = busMemberCardService.count(lambdaQueryWrapper2);
						if (count == 0) {
							LambdaQueryWrapper<BusMarketMember> lambdaQueryWrapper = new LambdaQueryWrapper<>();
							lambdaQueryWrapper.eq(BusMarketMember::getHotelId, hotelId);
							lambdaQueryWrapper.eq(BusMarketMember::getName, t.getGradeId());
							List<BusMarketMember> busMarketMembers = busMarketMemberService.list(lambdaQueryWrapper);
							if (ObjectUtils.isNotEmpty(busMarketMembers)) {
								t.setGradeId(busMarketMembers.get(0).getId());
							}
							t.setCreateTime(DateTime.now());
							t.setHotelId(hotelId);
							t.setTenantId(user.getRelTenantIds());
							addList.add(t);
						}
					}
				});
				service.saveBatch(addList);
				//400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
				//1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				//update-end-author:taoyan date:20190528 for:批量插入数据
				return Result.ok("文件导入成功！数据行数：" + addList.size());
			} catch (Exception e) {
				//update-begin-author:taoyan date:20211124 for: 导入数据重复增加提示
				String msg = e.getMessage();
				log.error(msg, e);
				if (msg != null && msg.indexOf("Duplicate entry") >= 0) {
					return Result.error("文件导入失败:有重复数据！");
				} else {
					return Result.error("文件导入失败:" + e.getMessage());
				}
				//update-end-author:taoyan date:20211124 for: 导入数据重复增加提示
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}
}
